#!/bin/sh
## java env
##export JAVA_HOME=/usr/local/jdk1.8
##export JRE_HOME=$JAVA_HOME/jre

     ## service name
     SERVICE_NAME=$2
     VERSION=$3
     ACTIVE=$4
     lastday=`date -d 'yesterday' +%Y%m%d`
     today=`date +%Y%m%d`
     JAR_NAME=$SERVICE_NAME-$VERSION.$today.jar
     HISTORY_JAR_NAME=`ls|grep -v  $JAR_NAME|grep -v *.sh|grep -v lastDeploy|grep -v logs|grep -v config|grep -v pid`
     PID=pid/${SERVICE_NAME}\.pid
     HOME="${BASH_SOURCE-$0}"
     HOME="$(dirname "${HOME}")"
     HOME="$(cd "${HOME}"; pwd)"
     WORK_DIR=$HOME/${JAR_NAME}


#function start
start(){
   cd $HOME
   if [ ! -d "logs" ]; then
        mkdir logs
    fi
    if [ ! -d "pid" ]; then
        mkdir pid
    fi
    if [ ! -n "$ACTIVE" ] ;then
        nohup java -Xms256m -Xmx512m -jar $WORK_DIR >logs/$SERVICE_NAME.out 2>&1 &
    else
        nohup java -Xms256m -Xmx512m -jar $WORK_DIR --spring.profiles.active=$ACTIVE >logs/$SERVICE_NAME.out 2>&1 &
    fi
        echo $! > $HOME/$PID
        echo "#### start $SERVICE_NAME"
}
# function stop
stop(){
       cd $HOME
       if [ -f "$HOME/$PID" ]; then
            kill `cat $HOME/$PID`
            rm -rf $HOME/$PID
        fi
        echo "#### stop $HOME"
        sleep 3
        TEMP_PID=`ps -ef | grep -w "$HOME" | grep -v "grep" | awk '{print $2}'`
        echo "#### TEMP_PID $TEMP_PID"
        if [ "$TEMP_PID" == "" ]; then
            echo "#### $HOME process not exists or stop success"
        else
            echo "#### $HOME process pid is:$TEMP_PID ."
            kill -9 $TEMP_PID
        fi
}
# function clean
clean(){
        cd $HOME
        if [ ! -d "lastDeploy" ]; then
           mkdir lastDeploy
        fi
        for i in $HISTORY_JAR_NAME
        do
            echo "### mv $i  to lastDeploy"
            mv $i lastDeploy
        done
}
case "$1" in
    start)
        
        start
        ;;
    stop)
        
        stop
        ;;
    restart)
        
        stop
        sleep 2
        start
        echo "#### restart $SERVICE_NAME"
        ;;
    clean)
        
        stop
        sleep 2
        clean
        echo "#### clean $SERVICE_NAME"
   ;;
    deploy)
      
      stop
      sleep 2
      clean
      sleep 2
      start
      echo "#### deploy $SERVICE_NAME"
   ;;
    *)
      echo 'hi,this is help...脚本执行命令如下'
      echo "./deploy.sh 执行方法 服务名 版本 运行环境"
      echo "example: ./deploy.sh start lts 0.0.1 dev"
       ;;
esac
exit 0